import { httpRequest } from "./open-api.js";
import axios from 'axios';
/**
 * 获取所有店铺
 * @param {*} appId 
 * @param {*} data accessToken
 * @returns 
 */
export async function getDianPuList(appId, data) {
  const path = "/erp/sc/data/seller/lists";
  const res = await httpRequest(path, 'get', appId, data ? data.access_token : '',null)
  return res
}
/**
 * 获取店铺下的listing
 * @param {*} appId 
 * @param {*} data accessToken
 * @param {*} sid 店铺的Sid
 * @returns 
 */
export async function getListingBySid(appId, data,sid) {
    const path = "/erp/sc/data/mws/listing";
    const params = {sid:sid}
    const res = await httpRequest(path, 'post', appId, data ? data.access_token : '',params);
    let arr = []
    res.data.forEach(element => {
        const obj = {
           asin:element.asin,
           principal_info:element.principal_info[0]
        }
        arr.push(obj)
    });
    return arr
}
/**
 * 获取店铺销量
 * @param {*} appId 
 * @param {*} data accessToken
 * @param {*} sid 店铺id
 * @param {*} date 日期
 * @returns 
 */

export async function getSaleBySid(appId, data,sid,date) {
    const path = "/erp/sc/data/sales_report/asinDailyLists";
    const params = {sid:sid,event_date:date}
    const res = await httpRequest(path, 'post', appId, data ? data.access_token : '',params);
    return res
}

/**
 * 获取所有的用户信息
 * @param {*} appId 
 * @param {*} data 
 * @returns 
 */
export async function getUserInfo(appId, data) {
    const path = "/erp/sc/data/account/lists";
    const params =null;
    const res = await httpRequest(path, 'get', appId, data ? data.access_token : '',params);
    return res
}
/**
 * API鉴权
 */
  export async function getAuthToken(apiKey, apiSecret) {
    const url = "https://open-platform.itasaas.com/api/v1/auth/get-token";  // API URL
    
    const headers = {
        "Content-Type": "application/json"
    };

    const body = {
        apiKey: apiKey,
        secretKey: apiSecret
    };

    try {
        const response = await axios.post(url, body, { headers: headers });
        return response.data;  // 假设返回的响应有 'access_token' 字段

    } catch (error) {
        console.error('Error fetching token:', error);
    }
}
/**
 * 零星同步销售数据
 * @param {string} accessToken - 之前获取的 access_token.
 * @param {object} saleData - 销售数据要同步的内容.
 * @returns {Promise} - 返回请求的 Promise.
 */
export async function syncLingXingSales(accessToken, saleData) {
    try {
      const response = await axios.post(
        'https://open-platform.itasaas.com/api/v1/lingxing-sale/sync',
        saleData, // 请求体，包含要同步的销售数据
        {
          headers: {
            'Authorization': `Bearer ${accessToken.data}`, // 将 access_token 放在 Authorization 头中
            'Transfer-Encoding': 'chunked',
            'Content-Type': 'application/json' // 确保请求体是 JSON 格式
          }
        }
      );
      return response.data;
    } catch (error) {
      console.error('同步失败:', error.response ? error.response.data : error.message);
      throw error;
    }
  }
  